<template>
  <div class="student-table">
    <!-- 新增操作按钮区域 -->
    <div class="table-actions">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="warning" @click="handleEdit" :disabled="!selectedStudent">编辑</el-button>
      <el-button type="danger" @click="handleDelete" :disabled="!selectedStudent">删除</el-button>
      <!-- 新增排序下拉框 -->
      <el-select v-model="sortField" placeholder="排序字段" style="width: 120px; margin-left: 10px">
        <el-option label="按学号" value="studentId" />
        <el-option label="按生日" value="birthDate" />
      </el-select>
      
      <el-select v-model="sortOrder" placeholder="排序方式" style="width: 120px; margin-left: 10px">
        <el-option label="升序" value="asc" />
        <el-option label="降序" value="desc" />
      </el-select>
    </div>

     

    <el-table 
      :data="students" 
      @row-click="handleRowClick"
      highlight-current-row>
      <el-table-column prop="studentId" label="学号" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="birthDate" label="生日" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column prop="className" label="班级" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="major" label="专业" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column label="图像">
        <template #default="scope">
          <img :src="scope.row.fileDataToSrc" alt="图像" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column label="音频" width="280">
        <template #default="scope">
          <audio :src="scope.row.fileDataAudioToSrc || ''" controls style="width: 250px; height: 30px"></audio>
        </template>
      </el-table-column>
      <el-table-column label="视频" width="280">
        <template #default="scope">
          <video :src="scope.row.fileDataVideoToSrc || ''" controls style="width: 250px; height: 80px"></video>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 添加/编辑 学生对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600" @close="closeHandle">
    <el-form :model="studentInfo" label-width="100px" :rules="rules" ref="formRef">
      <el-form-item label="学号" prop="studentId">
        <el-input v-model="studentInfo.studentId" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="studentInfo.name" />
      </el-form-item>
      <el-form-item label="生日" prop="birthDate">
        <el-date-picker v-model="studentInfo.birthDate" type="date" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="studentInfo.gender">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="className">
        <el-input v-model="studentInfo.className" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="studentInfo.phone" />
      </el-form-item>
      <el-form-item label="专业" prop="major">
        <el-input v-model="studentInfo.major" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="studentInfo.email" />
      </el-form-item>
      
      <el-form-item label="照片" prop="photo">
        <el-upload
          ref="uploadRef"
          :http-request="handleUpload"
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </template>
        </el-upload>
      </el-form-item>

        <el-form-item label="音频">
          <el-upload
            ref="uploadRefAudio"
            :http-request="handleUploadAudio"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            :on-exceed="handleExceedAudio"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="视频">
          <el-upload
            ref="uploadRefVideo"
            :http-request="handleUploadVideo"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            :on-exceed="handleExceedVideo"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { StudentInfo } from '@/info/StudentInfo';
import api from '@/api';

const students = ref<StudentInfo[]>([]);
const selectedStudent = ref(null);
const studentInfo = reactive<StudentInfo>(new StudentInfo());
const dialogVisible = ref(false);
const formRef = ref();
// 添加对话框标题变量
const dialogTitle = ref('添加学生'); 
// 新增排序相关变量
const sortField = ref('studentId');
const sortOrder = ref('asc');
const uploadRef = ref(); 
const uploadRefAudio = ref(); 
const uploadRefVideo = ref(); 
// 图像上传
let formData = new FormData();
// 音频上传
let formData1 = new FormData();
// 视频上传
let formData2 = new FormData();

onMounted(()=>{
  getStudent();
});

function handleRowClick(row){
  selectedStudent.value = row;
}

// 修改getStudent方法，添加排序参数
async function getStudent(){
  const res = await api.student.getStudentList({
    sortField: sortField.value,
    sortOrder: sortOrder.value
  });

  let temp_ = res.map(item => {
    item.fileDataToSrc = getFileDataToSrc(item.fileData);
    item.fileDataAudioToSrc = getAudioToSrc(item.audioData);
    item.fileDataVideoToSrc = getVideoToSrc(item.videoData);
    return item;
  })
  // console.log(temp_);
  students.value = temp_;
}

// 将Blob图像转为可以查看的图片URL
function getFileDataToSrc(blobData) {
  if (!blobData) return '';
  // 如果已经是base64字符串，直接返回
  if (typeof blobData === 'string') {
    return blobData.startsWith('data:') ? blobData : `data:image/jpeg;base64,${blobData}`;
  }
  // 处理Blob对象
  return URL.createObjectURL(new Blob([blobData]));
}

// 将Blob音频转为可以播放的URL
function getAudioToSrc(blobData) {
  if (!blobData) return '';
  // 如果已经是base64字符串，直接返回
  if (typeof blobData === 'string') {
    return blobData.startsWith('data:') ? blobData : `data:audio/mp3;base64,${blobData}`;
  }
  // 处理Blob对象
  return URL.createObjectURL(new Blob([blobData], { type: 'audio/mp3' }));
}

// 将Blob视频转为可以播放的URL
function getVideoToSrc(blobData) {
  if (!blobData) return '';
  // 如果已经是base64字符串，直接返回
  if (typeof blobData === 'string') {
    return blobData.startsWith('data:') ? blobData : `data:video/mp4;base64,${blobData}`;
  }
  // 处理Blob对象
  return URL.createObjectURL(new Blob([blobData], { type: 'video/mp4' }));
}

// 添加watch监听排序变化
watch([sortField, sortOrder], () => {
  console.log(11)
  getStudent();
});

async function handleAdd(){
  dialogTitle.value = '添加学生';
  dialogVisible.value = true;
  Object.assign(studentInfo, new StudentInfo());
  // 重置FormData对象
  formData = new FormData();
  formData1 = new FormData();
  formData2 = new FormData();
  
  // 清除所有上传文件
  uploadRef.value?.clearFiles();
  uploadRefAudio.value?.clearFiles();
  uploadRefVideo.value?.clearFiles();

}

async function handleEdit(){
  if (!selectedStudent.value) return;
  
  dialogTitle.value = '编辑学生';
  dialogVisible.value = true;
  Object.assign(studentInfo, selectedStudent.value);
}

// 图像上传
async function handleUpload(options: any) {
  formData.append('file', options.file);
}
// 音频上传
async function handleUploadAudio(options: any) {
  formData1.append('file', options.file);
}
// 视频上传
async function handleUploadVideo(options: any) {
  formData2.append('file', options.file);
}

async function submitForm() {
  try {
    await formRef.value.validate();
    uploadRef.value.submit();
    uploadRefAudio.value.submit();
    uploadRefVideo.value.submit();

    if (dialogTitle.value === '添加学生') {
      let res = await api.student.addStudent(studentInfo);
      try {
        await api.student.uploadFile(formData, res.studentId);
        await api.student.uploadFileAudio(formData1, res.studentId);
        await api.student.uploadFileVideo(formData2, res.studentId);
        await getStudent();
        ElMessage.success('添加成功');
      } catch (error) {
        // ElMessage.error('添加失败');
      }

    } else {
      let res = await api.student.updateStudent(selectedStudent.value?.id, studentInfo);
      console.log(234, res.studentId);
      if(formData.get('file')){
        await api.student.uploadFile(formData, res.studentId);
      }
      if(formData1.get('file')){
        await api.student.uploadFileAudio(formData1, res.studentId);
      }
      if(formData2.get('file')){
        await api.student.uploadFileVideo(formData2, res.studentId);
      }
      ElMessage.success('更新成功');
      formData.delete('file');
      formData1.delete('file');
      formData2.delete('file');
      uploadRef.value.clearFiles();
      uploadRefAudio.value.clearFiles();
      uploadRefVideo.value.clearFiles();
    }
    await getStudent();
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error(error.message || '操作失败');
  }
}

async function handleDelete(){
  try {
    await ElMessageBox.confirm(
      '确定要删除该学生信息吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    await api.student.deleteStudent(selectedStudent.value?.id);
    selectedStudent.value = null;
    await getStudent();
    ElMessage.success('删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
}

// 表单验证规则
const rules = {
  studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
};

const handleExceed = (files: File[]) => {
  // 移除已选择的文件
  uploadRef.value.clearFiles();
  // 添加新选择的文件
  const file = files[0];
  file.uid = Date.now(); // 生成新的uid
  uploadRef.value.handleStart(file);
};
const handleExceedAudio = (files: File[]) => {
  // 移除已选择的文件
  uploadRefAudio.value.clearFiles();
  // 添加新选择的文件
  const file = files[0];
  file.uid = Date.now(); // 生成新的uid
  uploadRefAudio.value.handleStart(file);
};
const handleExceedVideo = (files: File[]) => {
  // 移除已选择的文件
  uploadRefVideo.value.clearFiles();
  // 添加新选择的文件
  const file = files[0];
  file.uid = Date.now(); // 生成新的uid
  uploadRefVideo.value.handleStart(file);
};


function closeHandle(){
  uploadRef.value.clearFiles();
  uploadRefAudio.value.clearFiles();
  uploadRefVideo.value.clearFiles();
}



</script>

<style scoped>
.student-table {
  padding: 20px;
}

.table-actions {
  margin-bottom: 20px;
}
</style>



<style scoped>
.avatar {
  width: 120px;
  height: 120px;
  margin: 10px 0 0 10px;
}
</style>

<style scoped>
/* 音频控制条样式 */
audio {
  width: 150px;
  height: 30px;
}
/* 或者更精确的控制 */
audio::-webkit-media-controls-panel {
  width: 150px;
  height: 30px;
  padding: 0;
}
</style>
